//
//  WebAccessUtil.m
//
//  Created by Billy on 15/7/7.
//  Copyright (c) 2015年 seven. All rights reserved.
//

#import "WebAccessUtil.h"
#import "AFNetworking.h"
#import "Baby.h"


@interface WebAccessUtil ()

@property (nonatomic,strong) AFHTTPRequestOperationManager *manager;

@end
@implementation WebAccessUtil


static WebAccessUtil* webUtil = nil;

+ (WebAccessUtil *) shardWebUtil
{
    @synchronized([WebAccessUtil class])
    {
        if (!webUtil) {
            webUtil = [[[self class] alloc] init];
        }
        
        return webUtil;
    }
    
    
    return nil;
}


#pragma mark - AFnetworking method

//我家数据访问方法
- (void) accessMyFamilyUsingURLString:(NSString *) urlString  andParas:(id) params andTransferGottenDataBack:(transferValue) transfer {
    
    [self.manager POST:urlString parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:0 error:nil];
        
        //
        
        transfer ([self parseBabyDataByDictionary:dic]);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        ////NSLog(@"下载 错误:%@",error);
    }];
    
}

//我家数据解析方法
- (NSArray *)parseBabyDataByDictionary:(NSDictionary *) dic {
    
    NSMutableArray *MutableArray_allBabies = [NSMutableArray array]; //用于放所有的baby
    NSArray *array_allData = dic [@"dataList"];
    
    if ([array_allData count] != 0) {
        
        for (NSDictionary *dic_tmp in array_allData) {
            
            Baby *tmp = [[Baby alloc] init];
            
            tmp.baby_age = dic_tmp[@"babyAge"];
            tmp.baby_day = dic_tmp[@"babyDay"];
            tmp.baby_gender = dic_tmp[@"gender"];
            tmp.baby_height = dic_tmp[@"babyHeight"];
            tmp.baby_weight = dic_tmp[@"babyWeight"];
            tmp.baby_name = dic_tmp[@"babyName"];
            tmp.baby_id = dic_tmp[@"ID"];
            
            
            [MutableArray_allBabies addObject:tmp];
        }
    }

    return MutableArray_allBabies;
}



#pragma mark - AFnetworking manager getter

- (AFHTTPRequestOperationManager *) manager {
    
    if (!_manager) {
        
        _manager = [AFHTTPRequestOperationManager manager];
        _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    }
    
    return _manager;
}
@end
